package com.example.broadcastlistener;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import java.util.LinkedList;


/**
 * @author hdz
 * @date 2019/06/22
 */
public class MessageListFragment extends Fragment implements BroadcastListener.MessageReceiver {

    private MessageDetailAdapter mMessageDetailAdapter;
    private BroadcastListener mBroadcastListener;

    public MessageListFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_message_list, container, false);

        LinkedList<MessageDetail> mMessageDetail = new LinkedList<MessageDetail>();
        mMessageDetailAdapter = new MessageDetailAdapter(mMessageDetail, getContext());
        ListView mListView = (ListView) view.findViewById(R.id.message_list);
        mListView.setAdapter(mMessageDetailAdapter);

        mBroadcastListener = new BroadcastListener(getContext(), this);

        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onDestroy() {
        mBroadcastListener.destroy();
        super.onDestroy();
    }

    @Override
    public void onReceive(String action, String detail) {
        if (mMessageDetailAdapter != null) {
            mMessageDetailAdapter.add(0, new MessageDetail(action, detail));
        }
    }
}
